using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using WebSvrUpdaterCore.Models;
using WebUpdaterAdminCore.Data;
using WebUpdaterAdminCore.Models;
using WebUpdaterAdminCore.Utils;
using AutoMapper;
using Microsoft.Extensions.Logging;

namespace WebUpdaterAdminCore.WebApi
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class WebSiteInfoController : Controller
    {

        private ApplicationDbContext _dbContext;
        private UpdaterSocketServerService _socketServerService;
        private ILogger<WebSiteInfoController> _logger;
        public WebSiteInfoController(ApplicationDbContext dbContext,
            ILogger<WebSiteInfoController> logger,
            UpdaterSocketServerService updaterSocket)
        {
            _logger = logger;
            _dbContext = dbContext;
            _socketServerService = updaterSocket;
        }

        /// <summary>
        /// 请求客户端站点信息
        /// </summary>
        /// <param name="id">客户端SessionID</param>
        /// <param name="siteName">站点名称,如果为空表示请求所有站点信息</param>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<IActionResult> Query(string id, string siteName)
        {
            var svc = _socketServerService.GetSessionByID(id);
            if (svc != null)
            {
                if (string.IsNullOrEmpty(siteName))
                {
                    siteName = "#ALL#";
                }
                var uid = await svc.SendWebSiteInfoAsync(_dbContext, HttpContext.User.Identity.Name ?? "Test", new WebSiteInfoRequest { SiteName = siteName });
                return Json(new OKResult<string>(uid));
            }
            else
            {
                return Json(new ErrorResult(100102, "会话不存在或客户端未连接，请刷新后重试"));
            }
        }



        /// <summary>
        /// 请求站点信息结果
        /// </summary>
        /// <param name="id">发送请求返回的结果id</param>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<IActionResult> Result(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "请求参数不能为空"));
            }
            else
            {
                var msg = await SocketResponeHelper.GetRespone(id);
                if (msg != null && id.Equals(msg.RequestId,StringComparison.OrdinalIgnoreCase))
                {
                    var siteInfoRespone = msg.ReceiveData as WebSiteInfoRespone;
                    var list = new List<ClientWebSiteViewModel>();
                    if(siteInfoRespone != null)
                    {
                        var siteInfos = siteInfoRespone.SiteInfos;
                        foreach(var site in siteInfos)
                        {
                            
                            var siteExt = _dbContext.WebSiteInfoExtends.Find(site.Id.ToString());
                            var model = new ClientWebSiteViewModel
                            {                               
                                SiteInfo = site,
                                SiteInfoExtend = siteExt
                            };
                            list.Add(model);
                        }
                        msg.ReceiveData = list;
                    }
                    
                    return Json(new OKResult<MsgReceiveModel>(msg));
                }
                else
                {
                    return Json(new ErrorResult(100102, "请求尚未完成或者请求不存在"));
                }

            }
        }

        /// <summary>
        /// 创建站点
        /// </summary>
        /// <param name="id">socket会话ID</param>
        /// <param name="siteModel">站点模型</param>
        /// <returns></returns>
        [HttpPost("[action]/{id}")]
        public async Task<IActionResult> Create(string id,[FromBody]ClientWebSiteViewModel siteModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "客户端会话ID 不能为空"));
            }
            if(siteModel == null)
            {
                return Json(new ErrorResult(100101, "参数siteModel不能为空"));
            }
            var session = _socketServerService.GetSessionByID(id);
            if(session == null)
            {
                return Json(new ErrorResult(100102, "会话不存在或客户端未连接，请刷新后重试"));
            }
            else
            {
                var config = new MapperConfiguration(cfg => cfg.CreateMap<WebSiteInfoExtend, SiteInfoExtendModel>());
                var mapper = config.CreateMapper();
               
                var dto = mapper.Map<SiteInfoExtendModel>(siteModel.SiteInfoExtend);

                var request = new WebSiteAddRequest() { SiteModel = siteModel.SiteInfo,SiteInfoExtend = dto};
                var reqId = await session.SendWebSiteAddAsync(_dbContext, HttpContext.User.Identity.Name ?? "Test", request);
                var msg = await SocketResponeHelper.GetRespone(reqId, 100, 60);
               
                if(msg != null)
                {
                    var siteAddRespone = msg.ReceiveData as WebSiteAddRespone;
                    var siteExt = siteModel.SiteInfoExtend;

                    if (siteAddRespone != null && siteAddRespone.ResultCode == 0)
                    {
                        var siteId = siteAddRespone.WebSiteId;
                        
                        siteModel.SiteInfo.Id = siteId;
                        siteExt.SiteId = siteId.ToString();
                        var extModel = await _dbContext.WebSiteInfoExtends.FindAsync(siteExt.SiteId);
                        if (extModel == null)
                        {
                            _dbContext.WebSiteInfoExtends.Add(siteExt);
                        }
                        else
                        {
                            extModel.SiteName = siteModel.SiteInfo.SiteName;
                            extModel.BeforExecCommands = siteExt.BeforExecCommands;
                            extModel.AfterExecCommands = siteExt.AfterExecCommands;
                            extModel.SiteName = siteExt.SiteName;
                            extModel.TestAction = siteExt.TestAction;
                            extModel.WebAssemblyFileName = siteExt.WebAssemblyFileName;
                            extModel.WebPacketUrl = siteExt.WebPacketUrl;
                            extModel.WebPackMd5 = siteExt.WebPackMd5;
                            extModel.WebVersion = siteExt.WebVersion;
                            _dbContext.WebSiteInfoExtends.Update(extModel);
                        }
                        var count = await _dbContext.SaveChangesAsync();
                    }
                    
                   

                    return Json(new OKResult<MsgReceiveModel>(msg));
                }else
                {
                    return Json(new ErrorResult(100102, "请求尚未完成或者请求不存在,请求uid:"+reqId));
                }
                
            }
        }

        /// <summary>
        /// 检测站点名称是否可用
        /// </summary>
        /// <param name="id">socket会话ID</param>
        /// <param name="siteName">站点名称</param>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<IActionResult> CheckSiteName(string id,string siteName)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "客户端会话ID 不能为空"));
            }
            if (string.IsNullOrEmpty(siteName))
            {
                return Json(new ErrorResult(100101, "siteName不能为空"));
            }
            var session = _socketServerService.GetSessionByID(id);
            if (session == null)
            {
                return Json(new ErrorResult(100102, "会话不存在或客户端未连接，请刷新后重试"));
            }
            else
            {
                var request = new CheckSiteNameRequest
                {
                    SiteName = siteName
                };
                var reqId = await session.SendCheckSiteNameAsync(_dbContext, HttpContext.User.Identity.Name ?? "Test", request);
                var msg = await SocketResponeHelper.GetRespone(reqId);
                if (msg != null)
                {
                    return Json(new OKResult<MsgReceiveModel>(msg));
                }
                else
                {
                    return Json(new ErrorResult(100102, "请求尚未完成或者请求不存在"));
                }

                //return Json(new OKResult<string>(reqId));
            }
        }

        /// <summary>
        /// 修改站点
        /// </summary>
        /// <param name="id">socket会话ID</param>
        /// <param name="siteModel">站点模型</param>
        /// <returns></returns>
        [HttpPost("[action]/{id}")]
        public async Task<IActionResult> Modify(string id, [FromBody]ClientWebSiteViewModel siteModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "客户端会话ID 不能为空"));
            }
            if (siteModel == null)
            {
                return Json(new ErrorResult(100101, "参数siteModel不能为空"));
            }
            var session = _socketServerService.GetSessionByID(id);
            if (session == null)
            {
                return Json(new ErrorResult(100102, "会话不存在或客户端未连接，请刷新后重试"));
            }
            else
            {

            }
        }

        /// <summary>
        /// 删除站点
        /// </summary>
        /// <param name="id">socket会话ID</param>
        /// <param name="siteId">站点id</param>
        /// <returns></returns>
        [HttpPost("[action]/{id}")]
        public async Task<IActionResult> Delete(string id, [FromBody]string siteId)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "客户端会话ID 不能为空"));
            }
            if (string.IsNullOrEmpty(siteId))
            {
                return Json(new ErrorResult(100101, "参数siteId不能为空"));
            }
            var session = _socketServerService.GetSessionByID(id);
            if (session == null)
            {
                return Json(new ErrorResult(100102, "会话不存在或客户端未连接，请刷新后重试"));
            }
            else
            {

            }
        }

        /// <summary>
        /// 启动站点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="siteId">站点id</param>
        /// <returns></returns>
        [HttpPost("[action]/{id}")]
        public async Task<IActionResult> Start(string id, [FromBody]string siteId)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "客户端会话ID 不能为空"));
            }
            if (string.IsNullOrEmpty(siteId))
            {
                return Json(new ErrorResult(100101, "参数siteId不能为空"));
            }
            var session = _socketServerService.GetSessionByID(id);
            if (session == null)
            {
                return Json(new ErrorResult(100102, "会话不存在或客户端未连接，请刷新后重试"));
            }
            else
            {

            }
        }

        /// <summary>
        /// 停止站点
        /// </summary>
        /// <param name="id">socket会话ID</param>
        /// <param name="siteId">站点id</param>
        /// <returns></returns>
        [HttpPost("[action]/{id}")]
        public async Task<IActionResult> Stop(string id, [FromBody]string siteId)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "客户端会话ID 不能为空"));
            }
            if (string.IsNullOrEmpty(siteId))
            {
                return Json(new ErrorResult(100101, "参数siteId不能为空"));
            }
            var session = _socketServerService.GetSessionByID(id);
            if (session == null)
            {
                return Json(new ErrorResult(100102, "会话不存在或客户端未连接，请刷新后重试"));
            }
            else
            {
                session.SendWebSiteInfoAsync
            }
        }


    }
}
